package com.zyw.dev.zyw.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import com.zyw.dev.zyw.dao.ZJWBeans;
import com.zyw.dev.zyw.db.DataBaseHealper;
import com.zyw.dev.zyw.ui.activity.MainActivity;
import com.zyw.dev.zyw.utils.SMSTools;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by misl on 16/8/1.
 */
public class SmsReciver extends BroadcastReceiver {

    private DataBaseHealper dataBaseHealper;
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        SmsMessage msg = null;
        String body = null;
        if (null != bundle) {
            // 短信: Gas concentration 14% Wind speed 29.5m/s Illumination 0.00Lx Humidity 00RH Temperature 00C
            Object[] smsObj = (Object[]) bundle.get("pdus");
            for (Object object : smsObj) {
                msg = SmsMessage.createFromPdu((byte[]) object);
                Date date = new Date(msg.getTimestampMillis());//时间
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String receiveTime = format.format(date);
                body = msg.getDisplayMessageBody();
                if (null != body && body.indexOf("Gas concentration")>=0){
                    ZJWBeans beans = SMSTools.getZJWBeanBySMSBody(date,body);
//                    body = body.substring(body.indexOf("Gas")+4);
//                    String[] valus = body.split(" ");
//                    if (valus.length<10) continue;

//                    ZJWBeans beans = new ZJWBeans(null,date,valus[1].substring(0,valus[1].indexOf("%")),valus[4].substring(0,valus[4].indexOf("m/s")),
//                            valus[6].substring(0,valus[6].indexOf("Lx")),valus[8].substring(0,valus[8].indexOf("％RH")),valus[10].substring(0,valus[10].indexOf("C")));

                    dataBaseHealper = DataBaseHealper.newInstance();
                    dataBaseHealper.initDataBase();
                    long id = dataBaseHealper.insert(beans);
                    beans.setId(id);
                    Intent mIntent=new Intent(MainActivity.ACTION_INTENT_RECEIVER);
                    mIntent.putExtra("data",beans);
                    context.sendBroadcast(mIntent);
                }

                //在这里写自己的逻辑
                if (msg.getOriginatingAddress().equals("10086")) {
                    //TODO

                }

            }
        }
    }
}
